import axios from 'axios'
import Loading from '@/plugins/loading/index'
import { getToken } from '@u/index'
import { message } from 'antd';
import { createBrowserHistory } from 'history'
const history = createBrowserHistory();


const loading = Loading.getInstance();
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 8000
})
// 添加拦截
request.interceptors.request.use(function (config) {
  loading.showLoading();
  // 请求头添加token
  if (getToken()) {
    config.headers.token = getToken()
  }
  return config;
}, function (error) {
  loading.hideLoading();
  return Promise.reject(error);
});
request.interceptors.response.use(function (res) {
  loading.hideLoading();
  // 判断code 
  switch (res.data.code) {
    case 401:
      // 登录状态过期 弹出错误提示清除缓存并去 登录
      localStorage.removeItem("token");
      localStorage.removeItem("role");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("menus");
      message.error('登录状态过期请重新登录', 2, () => {
        // 去登录页
        history.replace('/login')
        history.go(0)
      })
      break;
    case 403:
      // 未登录 弹出错误提示去登录即可
      message.error('未登录请登录访问', 2, () => {
        // 去登录页
      })
    default:
      break;
  }
  return res;
}, function (error) {
  loading.hideLoading();
  return Promise.reject(error);
});

export default request